package com.jnu.student.view;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.jnu.student.R;
import com.jnu.student.data.Bill;
import com.jnu.student.data.BillDataBank;
import com.jnu.student.data.Book;
import com.jnu.student.data.BookItemDetailsActivity;
import com.jnu.student.data.achievementPointDataBank;
import com.jnu.student.data.DataBank;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;


public class dayTaskFragment extends Fragment implements OnDataChangeListener{

    ActivityResultLauncher<Intent> addItemLauncher;
    ActivityResultLauncher<Intent> updataItemLauncher;
    private double totalScore;

    private ArrayList<Book> books = new ArrayList<>();
    private BookItemAdapter bookItemAdapter;
    private DataBank dataBank;

    Button button;
    Button donebutton;
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private double achievementPoint;
    private achievementPointDataBank achievementDataBank;
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////





    public dayTaskFragment() {
        // Required empty public constructor
    }

    public static dayTaskFragment newInstance() {
        dayTaskFragment fragment = new dayTaskFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_day_task, container, false);

        RecyclerView mainrecyclerView = rootView.findViewById(R.id.recycle_view_books11);
        mainrecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));   //设置布局管理器

        dataBank = new DataBank();
        books = dataBank.loadShopItems(requireActivity());
        totalScore = dataBank.LoadTotalScore(requireActivity());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        bookItemAdapter = new BookItemAdapter(books);
        mainrecyclerView.setAdapter(bookItemAdapter);
        // 为适配器设置数据变更监听器
        bookItemAdapter.setOnDataChangeListener(this);

        registerForContextMenu(mainrecyclerView);         //注册ContextMenu事件菜单

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);//确保 ItemTouchHelper 已经附加到 RecyclerView 上。
        itemTouchHelper.attachToRecyclerView(mainrecyclerView);
        bookItemAdapter.setItemTouchHelper(itemTouchHelper);


        updataItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            int position = data.getIntExtra("position", -1);
                            String name = data.getStringExtra("name");
                            String scoreText = data.getStringExtra("score");

                            assert scoreText != null;
                            double score = Double.parseDouble(scoreText);
                            Book book = books.get(position);
                            book.setTitle(name);
                            book.setScore(score);
                            bookItemAdapter.notifyItemChanged(position);

                            new DataBank().SavebookItems(requireActivity(), books);
                        }
                    }
                });

        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null) {
                            String name = data.getStringExtra("name");
                            String scoreText = data.getStringExtra("score");

                            assert scoreText != null;
                            double score = Double.parseDouble(scoreText);
                            books.add(new Book(name, score));

                            //刷新
                            bookItemAdapter.notifyItemInserted(books.size());
                            new DataBank().SavebookItems(requireActivity(), books);
                        }
                    } // 处理取消操作

                });

        button = rootView.findViewById(R.id.button_add11);
        donebutton = rootView.findViewById(R.id.button_done11);

        boolean isAtLeastOneChecked = false;
        for (Book b : books) {
            if (b.isSelected()) {
                isAtLeastOneChecked = true;
                break;
            }
        }
        // 根据是否有条目被选中来显示或隐藏按钮
        donebutton.setVisibility(isAtLeastOneChecked ? View.VISIBLE : View.GONE);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件的逻辑
                Intent intent = new Intent(requireActivity(), BookItemDetailsActivity.class);
                addItemLauncher.launch(intent);
            }
        });

        donebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("确认完成");
                builder.setMessage("确认都完成了吗？");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确认按钮，执行删除数据的操作
                        Iterator<Book> iterator = books.iterator();

                        ArrayList<Bill> bills = new BillDataBank().loadBills(requireActivity());
                        LocalDate currentDate = LocalDate.now();

                        achievementDataBank = new achievementPointDataBank();
                        achievementPoint=achievementDataBank.loadAchievementPoints(requireActivity());
                        boolean dataChanged = false;
                        while (iterator.hasNext()) {
                            Book book = iterator.next();
                            if (book.isSelected()) {
                                double score = book.getScore(); //加载当前的分数
                                String title = book.getTitle(); // 加载当前的标题
                                totalScore += score;
                                achievementPoint += score;

                                // 创建一个新的账单对象
                                Bill bill = new Bill(title, score, currentDate); // 消费成就点，在账单里显示为负的，并附加当前日期
                                bills.add(bill);

                                iterator.remove(); // 在使用Iterator遍历时移除元素
                                dataChanged = true;
                            }
                        }

                        if (dataChanged) {

                            achievementDataBank.saveAchievementPoints(requireActivity(), achievementPoint);// 更新成就点数和总得分
                            new BillDataBank().saveBills(requireActivity(), bills); // 保存账单列表

                            dataBank.SaveTotalScore(requireActivity(), totalScore);
                            dataBank.SavebookItems(requireActivity(), books);

                            // 通知适配器数据发生了变化
                        }
                        bookItemAdapter.notifyDataSetChanged();
                        donebutton.setVisibility(View.GONE);

                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消按钮，不执行删除数据的操作
                        // 可以执行其他适当的操作或返回先前的界面

                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });



        return rootView;
    }

    @Override
    public void onDataChanged() {
        // 刷新界面
        if (isAdded()) { // 这将确保当 Fragment 附加到 Activity 时才执行更新操作
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    boolean isAtLeastOneChecked = false;
                    for (Book b : books) {
                        if (b.isSelected()) {
                            isAtLeastOneChecked = true;
                            break;
                        }
                    }
                    // 根据是否有条目被选中来显示或隐藏按钮
                    donebutton.setVisibility(isAtLeastOneChecked ? View.VISIBLE : View.GONE);
                }
            });
        }
    }



    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getGroupId() != 11) {
            return super.onContextItemSelected(item);
        }
        switch (item.getItemId()) {
            case 0:

                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("确认完成");
                builder.setMessage("确认完成了吗？");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确认按钮，执行删除数据的操作

                        Book book = books.get(item.getOrder());
                        double score = book.getScore();
                        String title =book.getTitle();//加载当前的分数
                        totalScore += score;

                        // 创建一个新的账单对象
                        // 创建一个新的账单对象，并获取当前日期
                        LocalDate currentDate = LocalDate.now();
                        Bill bill = new Bill(title, score, currentDate); // 消费成就点，在账单里显示为负的，并附加当前日期
                        // 加入到账单列表中
                        ArrayList<Bill> bills = new BillDataBank().loadBills(requireActivity());
                        bills.add(bill);
                        new BillDataBank().saveBills(requireActivity(), bills);


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        achievementDataBank = new achievementPointDataBank();
                        achievementPoint=achievementDataBank.loadAchievementPoints(requireActivity());
                        achievementPoint+=score;
                        achievementDataBank.saveAchievementPoints(requireActivity(),achievementPoint);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        books.remove(item.getOrder());
                        bookItemAdapter.notifyItemRemoved(item.getOrder());
                        dataBank.SaveTotalScore(requireActivity(), totalScore);
                        dataBank.SavebookItems(requireActivity(), books);


                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消按钮，不执行删除数据的操作
                        // 可以执行其他适当的操作或返回先前的界面

                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case 1:
                AlertDialog.Builder builder1 = new AlertDialog.Builder(requireActivity());
                builder1.setTitle("确认删除");
                builder1.setMessage("确认删除数据吗？");
                builder1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击确认按钮，执行删除数据的操作
                        books.remove(item.getOrder());
                        bookItemAdapter.notifyItemRemoved(item.getOrder());
                        new DataBank().SavebookItems(requireActivity(), books);

                    }
                });
                builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 用户点击取消按钮，不执行删除数据的操作
                        // 可以执行其他适当的操作或返回先前的界面

                    }
                });
                AlertDialog dialog1 = builder1.create();
                dialog1.show();
                break;
            // 可以继续添加其他的菜单项处理逻辑

            case 2:
                Intent intentUpdata = new Intent(requireActivity(), BookItemDetailsActivity.class);
                Book book = books.get(item.getOrder());
                intentUpdata.putExtra("name", book.getTitle());
                intentUpdata.putExtra("score", book.getScore());
                intentUpdata.putExtra("position", item.getOrder());

                updataItemLauncher.launch(intentUpdata);
                break;
            default:
                return super.onContextItemSelected(item);
        }

        return false;
    }



    public static class BookItemAdapter extends RecyclerView.Adapter<BookItemAdapter.ViewHolder> {

        private final ArrayList<Book> localDataSet;
        private ItemTouchHelper itemTouchHelper;

        public BookItemAdapter(ArrayList<Book> dataSet) {
            localDataSet = dataSet;
        }

        private OnDataChangeListener onDataChangeListener;
        public void setOnDataChangeListener(OnDataChangeListener onDataChangeListener) {
            this.onDataChangeListener = onDataChangeListener;
        }
        public void setItemTouchHelper(ItemTouchHelper itemTouchHelper) {
            this.itemTouchHelper = itemTouchHelper;
        }

        @NonNull
        @Override
        public dayTaskFragment.BookItemAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            // Create a new view, which defines the UI of the list item
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.book_item_row, viewGroup, false);

            return new dayTaskFragment.BookItemAdapter.ViewHolder(view, itemTouchHelper);
        }

        // Replace the contents of a view (invoked by the layout manager)
        @Override
        //绑定数据和View
        public void onBindViewHolder(BookItemAdapter.ViewHolder viewHolder, final int position) {

            // Get element from your dataset at this position and replace the
            // contents of the view with that element
            viewHolder.getTextViewName().setText(localDataSet.get(position).getTitle());
            viewHolder.getTextViewScore().setText("+ "+localDataSet.get(position).getScore());

            Book book = localDataSet.get(position);
            viewHolder.checkBox.setOnCheckedChangeListener(null); // 避免重用视图时触发事件
            viewHolder.checkBox.setChecked(book.isSelected());    // 根据当前状态设置复选框
            viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // 更新书本对象的状态
                    book.setSelected(isChecked);
                    new DataBank().SavebookItems(buttonView.getContext(),localDataSet);
                    // 如果有其他需要在此处处理的逻辑，比如回调，可以在这里实现
                    if (onDataChangeListener != null) {
                        onDataChangeListener.onDataChanged();
                    }

                }
            });
        }

        // Return the size of your dataset (invoked by the layout manager)
        @Override
        public int getItemCount() {
            return localDataSet.size();
        }

        /**
         * Provide a reference to the type of views that you are using
         * (custom ViewHolder).
         */
        public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final TextView textViewName;            //书名
            private final TextView textViewScore;

            private final CheckBox checkBox;
            private final ImageView imageView;
            private ItemTouchHelper itemTouchHelper; // 添加一个ItemTouchHelper实例的变量

            public ViewHolder(View view,ItemTouchHelper touchHelper) {
                super(view);
                // Define click listener for the ViewHolder's View

                textViewName = view.findViewById(R.id.book_title);
                textViewScore = view.findViewById(R.id.score);

                checkBox = view.findViewById(R.id.checkbox11);
                imageView = view.findViewById(R.id.drag_handle11);
                this.itemTouchHelper = touchHelper; // 设置ItemTouchHelper实例
                imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        // 当imageView被长按时，触发拖动
                        if (itemTouchHelper != null) {
                            itemTouchHelper.startDrag(ViewHolder.this);
                        }
                        return true;
                    }
                });

                view.setOnCreateContextMenuListener(this);
            }


            @Override
            //创建一个显示的菜单
            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");
                menu.add(11, 0, this.getAdapterPosition(), "完成");
                menu.add(11, 1, this.getAdapterPosition(), "删除");
                menu.add(11, 2, this.getAdapterPosition(), "修改");
            }


            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewScore() {
                return textViewScore;
            }
        }
    }
    ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {

        @Override
        public boolean isLongPressDragEnabled() {
            // 禁用长按触发拖动，因为我们会手动控制这个行为
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                              RecyclerView.ViewHolder target) {

            final int fromPosition = viewHolder.getAdapterPosition();
            final int toPosition = target.getAdapterPosition();

            // 对数据集进行操作以交换项的位置
            Collections.swap(books, fromPosition, toPosition);


            // 通知适配器项移动了
            bookItemAdapter.notifyItemMoved(fromPosition, toPosition);

            // 可选的，如果您有关联的数据变化或持久化的逻辑，可以在此处进行处理

            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // 这里处理滑动事件，本例中不需要



        }

        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {


                // 可以在此处创建一个扩散效果
                Drawable background = viewHolder.itemView.getBackground();
                if (background instanceof RippleDrawable) {
                    // 让 Ripple 效果运行
                    RippleDrawable rippleDrawable = (RippleDrawable) background;
                    rippleDrawable.setHotspot(viewHolder.itemView.getWidth() / 2f, viewHolder.itemView.getHeight() / 2f);
                    rippleDrawable.setState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled});
                } else {
                    // 创建并设置一个新的 RippleDrawable
                    ColorStateList rippleColor = ColorStateList.valueOf(Color.WHITE);
                    Drawable contentDrawable = new ColorDrawable(Color.LTGRAY); // 您可以自定义这个为任何你想要的 Drawable
                    RippleDrawable rippleDrawable = new RippleDrawable(rippleColor, contentDrawable, null);
                    viewHolder.itemView.setBackground(rippleDrawable);
                    rippleDrawable.setHotspot(viewHolder.itemView.getWidth() / 2f, viewHolder.itemView.getHeight() / 2f);
                    rippleDrawable.setState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled});
                }
            }
        }

        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);


            // 清除之前设置的背景等
            viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);

        }
    };
}